package org.asiainfo.common.core.utils.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.asiainfo.common.core.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件处理工具类
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public class FileUtils extends FileUtil {

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) {
        String percentEncodedFileName = percentEncode(realFileName);
        String contentDispositionValue = "attachment; filename=%s;filename*=utf-8''%s".formatted(percentEncodedFileName, percentEncodedFileName);
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue);
        response.setHeader("download-filename", percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
        return encode.replaceAll("\\+", "%20");
    }

    /**
     * 获取文件MD5
     *
     * @param file 上传文件
     * @return md5
     */
    public static String getFileMD5(MultipartFile file) {
        try {
            byte[] bytes = file.getBytes();
            return DigestUtil.md5Hex(bytes);
        } catch (Exception e) {
            log.info("获取文件MD5失败:{}", e.getMessage());
            // 处理异常
            return "";
        }
    }

    /**
     * MultipartFile 转 File
     *
     * @param file 文件
     * @throws Exception 报错信息
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File tempFile = FileUtil.createTempFile();
        try (OutputStream out = new FileOutputStream(tempFile)) {
            out.write(file.getBytes());
        }
        return tempFile;
    }
}
